<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <link rel="shortcut icon" href="/juanpao.ico"/>
    <title>手机在线客服</title>
    <meta name="viewport" content="width=device-width,minimum-scale=1.0,maximum-scale=1.0,user-scalable=no"/>
    {load href="__libs__/push/pusher.min.js"/}
    {load href="__libs__/jquery/jquery.min.js"/}
    {load href="__libs__/layui/layui.js"/}
    {load href="__libs__/jquery/jquery.cookie.js"/}
    <link rel="stylesheet" type="text/css" href="__style__/mobile/mobile.css?v=1.3">
    {load href="__libs__/jquery/jquery.form.min.js"/}
    {load href="__libs__/layer/skin/layer.css"/}
    {load href="__libs__/layui/css/layui.css"/}
    {load href="__libs__/layer/layer.js"/}

    <script type="text/javascript" src="/assets/libs/webrtc/recorder.js"></script>
    <script>
        var visiter ='{$visiter}';
        var business_id  ='{$business_id}';
        var record='{$from_url}';
        record.replace("%23","#");
        record.replace("%26","&");
        var pic ='{$avatar}';
        var channel= '{$channel}';
        var visiter_id= '{$visiter_id}';

        var cid ='{$groupid}';
        var url ='{$url}';
        if (pic == "") {
            pic = "/assets/images/index/avatar-red2.png";
        }
         var service_id=0;
        var wolive_connect =function () {
            
                    var pusher = new Pusher('{$app_key}', {encrypted: {$value}
                        ,enabledTransports: ['ws']
                        ,wsHost: '{$whost}'
                        ,{$port}: {$wport}
                        ,authEndpoint: '/auth.php'
                        ,disableStats: true
                    });

                    var channels = pusher.subscribe("cu" + channel);
                    channels.bind('my-event', function (data) {
                    
                        var msg = '';
                        msg += '<li class="chatmsg"><div style="position: absolute;top:2px;left:3px;">';
                        msg += '<img class="my-circle  se_pic" src="' + data.message.avatar + '" width="40px" height="40px"></div>';
                        msg += "<div class='outer-left'><div class='service'>";
                        msg += "<pre>" + data.message.content + "</pre>";
                        msg += "</div></div>";
                        msg += "</li>";
                        $(".chatmsg_notice").remove();
                        $(".chatmsg_no").remove();
                        $(".conversation").append(msg);
                        var div = document.getElementById("wrap");
                        div.scrollTop = div.scrollHeight;
                    });

                    channels.bind('first_word',function(data){
                    var msg = '';
                        msg += '<li class="chatmsg_no"><div style="position: absolute;left:3px;">';
                        msg += '<img class="my-circle  se_pic" src="' + data.message.avatar + '" width="40px" height="40px"></div>';
                        msg += "<div class='outer-left'><div class='service'>";
                        msg += "<pre>" + data.message.content + "</pre>";
                        msg += "</div></div>";
                        msg += "</li>";

                        $(".conversation").append(msg);

                    });

                    channels.bind('cu_notice', function (data) {
                        $("#img_head").attr("src", data.message.avatar);
                        $("#services").text(data.message.nick_name);
                        $(".chatmsg_notice").remove();
                        $.cookie("services",data.message.service_id);
                        service_id =data.message.service_id;
                        getquestion(business_id);
                        getdata();
                    });

                   function getlisten(chas){
                        var channels = pusher.subscribe("se"+chas);

                        //通知游客 客服离线
                        channels.bind('logout', function (data) {
                            $("#status").text("[离线]");
                        });
                        //表示客服在线
                        channels.bind("geton", function (data) {
                            $("#status").text('');
                        });
                    }
                    if($.cookie("services")){
                        var id =$.cookie("services");
                        getlisten(id);
                    }

                     pusher.connection.bind('state_change', function(states) {
                        if(states.current == 'unavailable' || states.current == "disconnected" || states.current == "failed" ){
                            $.cookie("cid","");
                            var id =$.cookie("services");
                            if(id){
                              pusher.unsubscribe("se"+id);
                            }

                            pusher.unsubscribe("cu" + channel);
                             if (typeof pusher.isdisconnect == 'undefined') {
                                    pusher.isdisconnect = true;   
                                    pusher.disconnect();
                                    delete pusher; 
                                    window.setTimeout(function(){
                                            wolive_connect();
                                      },1000);
                             }                           
                         }
                    });

                    pusher.connection.bind('connected', function() {
                        $.cookie("cid","");
                    
                    });
                }


    </script>
    <style type="text/css">

        #close_icon {
            position: absolute;
            right: 10px;
            top: 2px;
            cursor: pointer;
        }

        .input-but {
            position: relative;
            display: inline-block;
            vertical-align: middle;
            width: 30px;
            height: 30px;

        }

        .my-circle {
            border-radius: 30px;
        }

        .size {
            min-width: 30px;
            height: 25px;
            line-height: 30px;
            border: none;
        }

        .fileinput {
            width: 30px;
            height: 30px;
            position: absolute;
            top: 0px;
            right: 0px;
            opacity: 0;
            filter: alpha(opacity=0);
            cursor: pointer;
        }

         .chatmsg_no{
             position: relative;
             margin-bottom: 80px;
        }
     
       .chatmsg_question{
             position: relative;
             margin-bottom: 228px;
        }

    </style>
</head>
<body>
<div id="container">
    <div class="header">

        <span id="services" style="color: #FFF;"></span><span id="status"></span>

    </div>
    <div class="content" id="wrap">
        <ul class="conversation" >

        </ul>
    </div>

    <div class="foot_all">
        <div class="tool_box">
            <div class="wl_faces_content">
                <div class="wl_faces_main">
                    
                </div>
            </div>
        </div>

        <div class="foot_msg">
            <div class="msg-toolbar">
                <a id="face_icon" href="javascript:" onclick="faceon()"><i class="layui-icon" style="font-size: 26px;">&#xe60c;</i></a>

                {if $atype == 'open'}
                <a onclick="getaudio()"><i class="layui-icon" style="font-size: 22px;cursor: pointer;">&#xe688;</i></a>
                {/if}
                
                <a id="images" href="javascript:">
                    <form id="picture" enctype="multipart/form-data">
                        <div class="layui-box input-but  size">
                            <i class="layui-icon" style="font-size: 30px;">&#xe60d;</i>
                            <input type="file" name="upload" class="fileinput" onchange="put()"/>
                        </div>
                    </form>
                </a>
                <a id="files" href="javascript:">
                    <form id="file" enctype="multipart/form-data">
                        <div class="layui-box input-but  size">
                            <i class="layui-icon" style="font-size: 25px;">&#xe61d;</i>
                            <input type="file" name="folder" class="fileinput" onchange="putfile()"/>
                        </div>
                    </form>
                </a>
            </div>
            <div class="footer" style="margin-bottom: 30px;">
                <input type="text" id="text_in"  class="layui-input"  style="margin-top: 1px;margin-left:5px;width: 80%"/>
                <button class="layui-btn layui-btn-normal" style="position: absolute;right: 5px;top:1px;width: 17.5%"
                        onclick="send()">发送
                </button>
            </div>
        </div>
    </div>
</div>
<script type="text/javascript" src="__script__/moblie/mochat.js?v=1.5"></script>
<script>
   
    var getaudio =function(){

     var sid =$.cookie('services');
     if(sid == service_id){

         //音频先加载
                var audio_context;
                var recorder;
                var wavBlob;
                //创建音频
                try {
                    // webkit shim
                    window.AudioContext = window.AudioContext || window.webkitAudioContext;
                    navigator.getUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.msGetUserMedia || navigator.mediaDevices.getUserMedia;
                    window.URL = window.URL || window.webkitURL;

                    audio_context = new AudioContext;

                    if (!navigator.getUserMedia) {
                        console.log('语音创建失败');
                    }
                    ;
                } catch (e) {
                    console.log(e);
                    return;
                }
                navigator.getUserMedia({audio: true}, function (stream) {
                    var input = audio_context.createMediaStreamSource(stream);
                    recorder = new Recorder(input);

                    var falg = window.location.protocol;
                    if (falg == 'https:') {
                        recorder && recorder.record();

                        //示范一个公告层
                        layui.use(['jquery', 'layer'], function () {
                            var layer = layui.layer;

                            layer.msg('录音中...', {
                                icon: 16
                                , shade: 0.01
                                , skin: 'layui-layer-lan'
                                , time: 0 //20s后自动关闭
                                , btn: ['发送', '取消']
                                , yes: function (index, layero) {
                                    //按钮【按钮一】的回调
                                    recorder && recorder.stop();
                                    recorder && recorder.exportWAV(function (blob) {
                                        wavBlob = blob;
                                        var fd = new FormData();
                                        var wavName = encodeURIComponent('audio_recording_' + new Date().getTime() + '.wav');
                                        fd.append('wavName', wavName);
                                        fd.append('file', wavBlob);

                                        var xhr = new XMLHttpRequest();
                                        xhr.onreadystatechange = function () {
                                            if (xhr.readyState == 4 && xhr.status == 200) {
                                                jsonObject = JSON.parse(xhr.responseText);

                                                voicemessage = '<div style="cursor:pointer;text-align:center;" onclick="getstate(this)" data="play"><audio src="'+jsonObject.data.src+'"></audio><i class="layui-icon" style="font-size:25px;">&#xe652;</i><p>音频消息</p></div>';

                                                    var sid = $('#channel').text();
                                    
                                                    var time;

                                                    var sdata = $.cookie('cu_com');

                                                    if (sdata) {
                                                        var json = $.parseJSON(sdata);
                                                        var img = json.avater;

                                                    }

                                                       if($.cookie("itime") == ""){
                                                            var myDate = new Date();
                                                                time = myDate.getHours()+":"+myDate.getMinutes();
                                                            var timestamp = Date.parse(new Date());
                                                            $.cookie("itime",timestamp/1000);
                                                        
                                                        }else{

                                                            var timestamp = Date.parse(new Date());
                                                            var lasttime =$.cookie("itime");
                                                            if((timestamp/1000 - lasttime) >30){
                                                                var myDate =new Date(timestamp);
                                                                time = myDate.getHours()+":"+myDate.getMinutes();
                                                            }else{
                                                                time ="";
                                                            }

                                                            $.cookie("itime",timestamp/1000);
                                                        }
                                               
                                                var str = '';
                                                    str += '<li class="chatmsg"><div class="showtime">' + time + '</div>';
                                                    str += '<div style="position: absolute;top: 26px;right: 2px;"><img  class="my-circle cu_pic" src="' + pic + '" width="40px" height="40px"></div>';
                                                    str += "<div class='outer-right'><div class='customer'>";
                                                    str += "<pre>" +  voicemessage + "</pre>";
                                                    str += "</div></div>";
                                                    str += "</li>";

                                                    $(".conversation").append(str);
                                                    $("#text_in").empty();

                                                    var div = document.getElementById("wrap");
                                                    div.scrollTop = div.scrollHeight;

                                                   $.ajax({
                                                    url: "/admin/event/chat",
                                                    type: "post",
                                                    data: {visiter_id:visiter_id,content: voicemessage,business_id: business_id, avatar: pic,record: record,service_id:service_id},
                                                    dataType:'json',
                                                    success:function(res){
                                                        if(res.code != 0){
                                                            layer.msg(res.msg,{icon:2});
                                                        }
                                                    }
                                                });
                                            }
                                        };
                                        xhr.open('POST', '/admin/event/uploadVoice');
                                        xhr.send(fd);
                                    });
                                    recorder.clear();
                                    layer.close(index);
                                }
                                , btn2: function (index, layero) {
                                    //按钮【按钮二】的回调
                                    recorder && recorder.stop();
                                    recorder.clear();
                                    audio_context.close();
                                    layer.close(index);
                                }
                            });

                        });
                    } else {
                        
                            layer.msg('音频输入只支持https协议！');
                        
                    }


                }, function (e) {
                     layer.msg('音频输入只支持https协议！');
                });


        }
    }

  
   var getstate =function(obj){
       
       var c=obj.children[0];
 
       var state=$(obj).attr('data');
   
       if(state == 'play'){
         c.play();
         $(obj).attr('data','pause');
         $(obj).find('i').html("&#xe651;");
       
       }else if(state == 'pause'){
          c.pause();
         $(obj).attr('data','play');
          $(obj).find('i').html("&#xe652;");
       }

        c.addEventListener('ended', function () {  
         $(obj).attr('data','play');
         $(obj).find('i').html("&#xe652;");
        
       }, false);
    }

   


   document.getElementById("wrap").onscroll = function(){
        var t =  document.getElementById("wrap").scrollTop;
        if( t == 0 ) {
            if($.cookie("cid") != ""){
                getdata();
            }
        }
    }
    


</script>
</body>
</html>
